import React, { PureComponent } from 'react';
import { Upload, Icon, Spin } from 'antd';
import material from '../../services/cms/material';
import styles from './index.less';

function beforeUpload(file) {
  const isImage = ['image/gif', 'image/png', 'image/jpeg', 'image/bmp', 'image/webp'].includes(
    file.type
  );
  const isLt2M = file.size / 1024 / 1024 < 5;
  return isImage && isLt2M;
}

export default class ArticleCover extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      imageUrl: '',
    };
  }

  handleChange = info => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
    }
  };

  customRequest = option => {
    const { file } = option;
    const { onChange } = this.props;
    material.add({ name: file.name, file, description: file.name }).then(({ data }) => {
      this.setState({
        imageUrl: data.url,
        loading: false,
      });
      onChange(data.url);
    });
  };

  render() {
    const imageUrl = this.state.imageUrl || this.props.value || '';

    const image = (
      <div className={styles.cover}>
        <Spin spinning={this.state.loading}>
          <img src={imageUrl} alt="cover" />
        </Spin>
      </div>
    );

    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );

    return (
      <Upload
        name="cover"
        listType="picture-card"
        showUploadList={false}
        action=""
        beforeUpload={beforeUpload}
        customRequest={this.customRequest}
        onChange={this.handleChange}
      >
        {imageUrl ? image : uploadButton}
      </Upload>
    );
  }
}
